package study

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

object wc02 {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setMaster("local[*]") setAppName ("wc")
    val context = new SparkContext(conf)
    context.setLogLevel("WARN")
    val streamingContext = new StreamingContext(context, Seconds(5))

    /**
     * spark03:9999 状态管理
     */
    val data: ReceiverInputDStream[String] = streamingContext.socketTextStream("spark03", 9999)
    val mapRDD: DStream[(String, Int)] = data.flatMap(_.split(" ")).map((_, 1))

    // 注意:state存在checkpoint中
    streamingContext.checkpoint("./ckp")

    val result: DStream[(String, Int)] = mapRDD.updateStateByKey(
      (values: Seq[Int], state: Option[Int]) => {
        val newValue: Int = values.sum + state.getOrElse(0)
        Option(newValue)
      }
    )

    result.print()

    streamingContext.start()
    streamingContext.awaitTermination()

    streamingContext.stop(stopSparkContext = true, stopGracefully = true)
  }

}
